package interview.springboot.javassit;

import org.apache.ibatis.javassist.*;

import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Test {
    public void modifyMethod() throws NotFoundException, CannotCompileException, IOException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        ClassPool pool = ClassPool.getDefault();

        CtClass ct = pool.getCtClass("top.ss007.Point");
        CtMethod m = ct.getDeclaredMethod("move");
        m.insertBefore("{ System.out.print(\"dx:\"+$1); System.out.println(\"dy:\"+$2);}");
        m.insertAfter("{System.out.println(this.x); System.out.println(this.y);}");

        ct.writeFile();
        //通过反射调用方法，查看结果
        Class pc = ct.toClass();
        Method move = pc.getMethod("move", int.class, int.class);
        Constructor<?> con = pc.getConstructor(int.class, int.class);
        move.invoke(con.newInstance(1, 2), 1, 2);

    }

}
